#include "tcpcliet.h"
#include "ui_tcpcliet.h"

TcpCliet::TcpCliet(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::TcpCliet)
{
    ui->setupUi(this);
    qRegisterMetaType<QAbstractSocket::SocketError>("QAbstractSocket::SocketError");
    client = new QTcpSocket(this);
    ifConnect = false;
    connect(client, SIGNAL(connected()), this, SLOT(InfoSent()));
    connect(client, SIGNAL(readyRead()), this, SLOT(dataRecv()));
}

TcpCliet::~TcpCliet()
{
    delete ui;
}

void TcpCliet::on_pushButton_clicked()
{
   if (ifConnect)
       sendContent();
   else qDebug("未建立连接");
}

void TcpCliet::InfoSent()
{
  int ret = client->write("connected!");
  if (ret <= 0)
  {
      qDebug("发送信息失败");
      closeSocket();
  }
}
void TcpCliet::dataRecv()
{
QString recvData = client->readAll();
if (recvData == "Ready")
{
    qDebug("ready!");
    ifConnect = true;
}
}

void TcpCliet::sendContent()
{
    int ret = client->write(ui->textEdit->toPlainText().toStdString().c_str());
    if (ret <= 0)
    {
        qDebug("发送信息失败2");
        closeSocket();
    }
}

void TcpCliet::closeSocket()
{
    client->abort();
    client->disconnect();
    ifConnect = false;
}


void TcpCliet::on_pushButton_2_clicked()
{
    closeSocket();
}

void TcpCliet::on_pushButton_3_clicked()
{
    client->connectToHost("192.168.0.165", 6666);
    if (!client->waitForConnected(1000))
    {
        qDebug()<<QString("SocketError: %1").arg((int)(client->error()));
        closeSocket();
    }
}
